package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inst.IProdInstService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.common.bo.RoleInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class VIKHandler extends AbstractAttrHandler {

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    public IProdInstService prodInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {

        List<RoleInfo> list = ContextUtil.getLoginInfo().getUserRoles();
        List<RoleInfo> vikList = list.stream().filter(s ->
            "790000107".equals(s.getSysRoleCode())
        ).collect(Collectors.toList());
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String serviceOfferId = this.querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
        String cateId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
        if ("1".equals(serviceOfferId)||"1068".equals(serviceOfferId)) {
            if (LocalKeyConsts.IS_VIK.equals(commonAttr.getFieldName()) || LocalKeyConsts.IS_VIK_NEW.equals(commonAttr.getFieldName())) {
                if (!(vikList == null || vikList.size() == 0)) {
                    commonAttr.setIsEdit("T");
                    commonAttr.setShowType("D");
                    KiteAttr attr = querySceneInstService
                        .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                    attr.setIsEdit("T");
                    attr.setShowType("D");
                    // 满足条件的产品不展示
                    if (needHideProduct(cateId)) {
                        commonAttr.setShowType("E");
                        attr.setShowType("E");
                    }
                    operateSceneInstService.setCommonAttr(sceneInstId, attr);
                } else {
                    commonAttr.setIsEdit("F");
                    commonAttr.setShowType("E");
                    KiteAttr attr = querySceneInstService
                        .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                    attr.setIsEdit("F");
                    attr.setShowType("E");
                    operateSceneInstService.setCommonAttr(sceneInstId, attr);
                }
            }
            if ("SERVICE_STATE_CODE".equals(commonAttr.getFieldName()) || "OPEN_DATE".equals(commonAttr.getFieldName())) {
                commonAttr.setIsEdit("F");
                commonAttr.setShowType("E");
                KiteAttr attr = querySceneInstService
                    .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                attr.setIsEdit("F");
                attr.setShowType("E");
                operateSceneInstService.setCommonAttr(sceneInstId, attr);
            }
        } else if ("1073".equals(serviceOfferId) || "2549".equals(serviceOfferId)) {
            if (LocalKeyConsts.IS_VIK.equals(commonAttr.getFieldName()) || LocalKeyConsts.IS_VIK_NEW.equals(commonAttr.getFieldName())) {
                // 不会为空
                KiteAttr attr = querySceneInstService
                    .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                // 工号不存在权限，隐藏属性
                if (!(vikList == null || vikList.size() == 0)) {
                    commonAttr.setIsEdit("T");
                    commonAttr.setShowType("D");
                    attr.setIsEdit("T");
                    attr.setShowType("D");
                } else {
                    commonAttr.setIsEdit("F");
                    commonAttr.setShowType("E");
                    attr.setIsEdit("F");
                    attr.setShowType("E");
                }
                operateSceneInstService.setCommonAttr(sceneInstId, attr);
            }
            if ("SERVICE_STATE_CODE".equals(commonAttr.getFieldName()) || "OPEN_DATE".equals(commonAttr.getFieldName())) {
                commonAttr.setIsEdit("F");
                commonAttr.setShowType("D");
            }
        } else {
            if (LocalKeyConsts.IS_VIK.equals(commonAttr.getFieldName()) || LocalKeyConsts.IS_VIK_NEW.equals(commonAttr.getFieldName()) ||
                LocalKeyConsts.VIK_BUSINESS_CODE.equals(commonAttr.getFieldName()) || LocalKeyConsts.VIK_BUSINESS_CODE_NEW.equals(commonAttr.getFieldName())) {
                if (!(vikList == null || vikList.size() == 0)) {
                    // 如果是否VIK为是，则VIK业务编码才展示
                    if (LocalKeyConsts.VIK_BUSINESS_CODE.equals(commonAttr.getFieldName()) || LocalKeyConsts.VIK_BUSINESS_CODE_NEW.equals(commonAttr.getFieldName())) {
                        commonAttr.setIsEdit("F");
                        commonAttr.setShowType("D");
                        // 满足条件的产品不展示
                        if (needHideProduct(cateId)) {
                            commonAttr.setShowType("E");
                        }
                        KiteAttr vikAttr = querySceneInstService
                            .getCommonAttr(sceneInstId, LocalKeyConsts.IS_VIK);
                        if (Objects.isNull(vikAttr)) {
                            vikAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.IS_VIK_NEW);
                        }
                        if (Objects.nonNull(vikAttr)) {
                            if (!"1".equals(vikAttr.getValue())) {
                                commonAttr.setShowType("E");
                                KiteAttr attr = querySceneInstService
                                    .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                                attr.setShowType("E");
                                operateSceneInstService.setCommonAttr(sceneInstId, attr);
                            }
                        } else {
                            // TODO: 临时
                            commonAttr.setShowType("E");
                        }
                    } else {
                        commonAttr.setIsEdit("F");
                        commonAttr.setShowType("D");
                        KiteAttr attr = querySceneInstService
                            .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                        attr.setIsEdit("F");
                        attr.setShowType("D");
                        // 满足条件的产品不展示
                        if (needHideProduct(cateId)) {
                            commonAttr.setShowType("E");
                            attr.setShowType("E");
                        }
                        operateSceneInstService.setCommonAttr(sceneInstId, attr);
                    }
                } else {
                    commonAttr.setIsEdit("F");
                    commonAttr.setShowType("E");
                    KiteAttr attr = querySceneInstService
                        .getCommonAttr(sceneInstId, commonAttr.getFieldName());
                    attr.setIsEdit("F");
                    attr.setShowType("E");
                    operateSceneInstService.setCommonAttr(sceneInstId, attr);
                }
            }
            if ("SERVICE_STATE_CODE".equals(commonAttr.getFieldName()) || "OPEN_DATE".equals(commonAttr.getFieldName())) {
                commonAttr.setIsEdit("F");
                commonAttr.setShowType("D");
            }
        }
        // 集团开户状态和开户时间 调用户列表接口获取展示, 过滤订购和核查转定
        if (KiteStringUtils.equalsAny(commonAttr.getFieldName(), "OPEN_DATE", "SERVICE_STATE_CODE") && !("1".equals(serviceOfferId) || "1012".equals(serviceOfferId))) {
            List<KitePosUserDTO> userInfos = querySceneInstService.getExtParameterValue(sceneInstId, "userInfos");
            if (KiteListUtils.isNotEmpty(userInfos)) {
                String openDate = "";
                String userServiceCode = "";
                for (KitePosUserDTO userInfo : userInfos) {
                    openDate = userInfo.getOpenDate();
                    if (KiteStringUtils.isNotEmpty(openDate)) {
                        Date openFormatDate = DateFormatUtils.parseDateToFormat(openDate, DateFormatUtils.DEFAULTPATTERN);
                        openDate = DateFormatUtils.formatDate(openFormatDate, DateFormatUtils.DEFAULTPATTERN);
                    }
                    List<KitePosAttrDTO> userAttrInfos = userInfo.getAttrs();
                    if (KiteListUtils.isNotEmpty(userAttrInfos)) {
                        userAttrInfos = userAttrInfos.stream().filter(userAttrInfo -> KiteStringUtils.equals(userAttrInfo.getCode(), "serviceStateCode")).collect(Collectors.toList());
                        if(KiteListUtils.isNotEmpty(userAttrInfos)){
                            userServiceCode = Optional.ofNullable(userAttrInfos.get(0)).map(userAttr -> userAttr.getValue()).orElse("");
                        }
                    }
                }
                if (KiteStringUtils.equals("OPEN_DATE", commonAttr.getFieldName())) {
                    commonAttr.setValue(openDate);
                    commonAttr.setValueDesc(openDate);
                }
                if (KiteStringUtils.equals("SERVICE_STATE_CODE", commonAttr.getFieldName())) {
                    commonAttr.setValue(userServiceCode);
                    List<StaticAttrDO> attrValues = commonAttr.getAttrValues();
                    if (KiteListUtils.isNotEmpty(attrValues)) {
                        for (StaticAttrDO staticAttr : attrValues) {
                            if (KiteStringUtils.isEqual(staticAttr.getAttrValue(), userServiceCode)) {
                                commonAttr.setValueDesc(staticAttr.getAttrValueDesc());
                            }
                        }
                    }
                }
            }
        }
        setCommonAttr(commonAttr);
    }


    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        List<RoleInfo> list = ContextUtil.getLoginInfo().getUserRoles();
        List<RoleInfo> vikList = list.stream().filter(s ->
            "790000107".equals(s.getSysRoleCode())
        ).collect(Collectors.toList());
        KiteAttr attr = querySceneInstService
            .getCommonAttrsByFieldName(sceneInstId, LocalKeyConsts.VIK_BUSINESS_CODE, "113");
        if (Objects.isNull(attr)) {
            attr = querySceneInstService
                .getCommonAttrsByFieldName(sceneInstId, LocalKeyConsts.VIK_BUSINESS_CODE_NEW, "113");
        }
        if (Objects.isNull(attr)) {
            return ErrorConsts.SUCCESS.getResult(true);
        }
        if (LocalKeyConsts.IS_VIK.equals(fieldName) || LocalKeyConsts.IS_VIK_NEW.equals(fieldName)) {
            // 工号不具备权限，隐藏
            if (!(vikList == null || vikList.size() == 0)) {
                // 是否VIK为否时，清空VIK业务单编码
                if (KiteStringUtils.isEqual("1", value)) {
                    attr.setIsNull("F");
                    attr.setIsEdit("T");
                    attr.setShowType("D");
                    if (Objects.isNull(attr.getValue()) && Objects.nonNull(attr.getOriginValue())) {
                        attr.setValue(attr.getOriginValue());
                        attr.setValueDesc(attr.getOriginValue());
                    }
                } else {
                    attr.setIsNull("T");
                    attr.setIsEdit("F");
                    attr.setShowType("H");
                    attr.setValue(null);
                    attr.setValueDesc(null);
                }
            } else {
                attr.setIsNull("T");
                attr.setIsEdit("F");
                attr.setShowType("E");
            }
            SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, attr);
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private boolean needHideProduct(String cateId) {
        String codea = DcPublicCache.getCodea("20211214001", "needHideProduct");
        if (KiteStringUtils.isNotEmpty(codea) && KiteStringUtils.equalsAny(cateId, codea.split(SymbolConsts.COMMA))) {
            return true;
        }
        return false;
    }

}
